package antidestiny.utilib.ui.fragment.explorer;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import antidestiny.utilib.Aide;

/**
 * Created by Hero on 2016/6/24.
 */
public class ExplorerFileFilter {
    int filterType;
    public static final int TYPE_DIR_ONLY = 1,
            SPECIFIC_FILE_TYPE = 4,
            DONT_FILTRATE = 8,
            TYPE_FILE_FILTER = 16;

    //小写的后缀名
    String suffix;
    FileFilter fileFilter;

    //制定过滤类型，如果过滤特定类型文件，提供后缀，不需要点.
    public ExplorerFileFilter(int filterType, String suffix, FileFilter fileFilter) {
        this.filterType = filterType;
        if (suffix!=null)
        this.suffix = suffix.toLowerCase();
        this.fileFilter = fileFilter;
    }

    //从指定文件夹下过滤文件用于用户选择
    List<FileItem> filtrate(File dir) {
        File[] files = dir.listFiles();
        ArrayList<FileItem> result = new ArrayList<>();
        if (files == null) return result;
        for (File f : files) {
            if (accept(f) || f.isDirectory())
                result.add(new FileItem(f));
        }
        return result;
    }

    boolean accept(File file) {
        switch (filterType) {
            case TYPE_DIR_ONLY:
                return file.isDirectory();
            case TYPE_FILE_FILTER:
                return fileFilter != null && fileFilter.accept(file);
            case SPECIFIC_FILE_TYPE:
                return file.getName().toLowerCase().endsWith('.' + suffix.toLowerCase());
            case DONT_FILTRATE:
                return true;
        }
        return false;
    }
}



